
var SaveImage = {
  autoShare(user, gate, score, plane,finishcb) {
    var asy = new CCAsync()
    this.canvas = wx.createCanvas()
    this.canvas.width = 500;
    this.canvas.height = 400;
    var strArr = ['无尽模式', '第一关', '第二关', '第三关', '第四关', '第五关', '第六关'];
    var userName = this.subSectionString(user.nickname, 12);
    var useScore = '分数:' + score;
    var userId = user.id;
    var shareStr = 'sharebg.png';
    var userHeadStr = user.headImgUrl;
    var planeStr = plane + '.png';
    var gateStr = strArr[gate] || strArr[0];
    let ctx = this.canvas.getContext('2d');
    ctx.font = 50 + "px Arial bold";
    var scoreStr = ctx.measureText(useScore);
    var px = (500 - scoreStr.width) / 2;

    asy.parallel([
      (cb) => { this.getFile(shareStr, 0, cb) },
      (cb) => { this.getFile(userHeadStr, userId, cb) },
      // (cb) => { this.getFile(planeStr, 0, cb) },
      (cb) => { this.getFile(planeStr, 0, cb) },
    ], (err, result) => {
      if (err) { return; }
      console.log('下载后的图片路径数组', result);
      var imgs = [
        { src: result[0], x: 0, y: 0, width: 500, height: 400 },
        { src: result[1], x: 54, y: 170, width: 64, height: 64 },
        { src: result[2], x: 310, y: 100, width: 160, height: 160 },
      ];
      var texts = [
        { text: useScore, x: px, y: 64, _px: 50, _color: '#64FFFF' },
        { text: gateStr, x: 60, y: 140, _px: 36, _color: '#64FFFF' },
        { text: userName, x: 130, y: 190, _px: 28, _color: '#FFFFFF' },
        { text: userId, x: 130, y: 230, _px: 28, _color: '#FFFFFF' }
      ];
      this.createShareImage(imgs, texts, (err,res) => {
        if(err){
          finishcb&&finishcb()
          return;
        }
        setTimeout(() => {
          this.canvas.toTempFilePath({
            x: 0, y: 0,
            width: 500, height: 400,
            destWidth: 500, destHeight: 400,
            fileType: 'png', quality: 1.0,
            success: (res) => {
              wx.shareAppMessage({
                title: '谁敢与我一战！',
                imageUrl: res.tempFilePath,
                // query: query,
                success: () => { },
                fail: () => { }
              });
            },
          });
          finishcb&&finishcb()
        }, 1000);
      })
    })
  },

  createShareImage(imgs, texts, finishcb) {
    let ctx = this.canvas.getContext('2d');
    var arr = [];
    for (let i = 0; i < imgs.length; i++) {
      let img = { x: 0, y: 0 }
      img = Object.assign(img, imgs[i])
      arr.push((d, c) => {
        let cb = c ? c : d;
        let image = wx.createImage();
        console.log('开始createImage', img.src);
        image.onload = () => {
          console.log('createImage成功', img.src, img);
          let width = img.width ? img.width : image.width;
          let height = img.height ? img.height : image.height;
          ctx.drawImage(image, img.x, img.y, width, height);
          cb(null, 1);
        }
        image.src = img.src;
      });
    }
    if (texts && texts.length > 0) {
      arr.push((d, cb) => {
        for (let i = 0; i < texts.length; i++) {
          let textinfo = { x: 0, y: 0 }
          textinfo = Object.assign(textinfo, texts[i]);
          let strs = textinfo.text || '';
          ctx.fillStyle = texts[i]._color;
          ctx.font = texts[i]._px + "px Arial bold";
          ctx.fillText(strs, textinfo.x, textinfo.y, 500);
        }
        cb(null, 1);
      });
    }
    arr.push(finishcb);
    let asc = new CCAsync();
    asc.waterfall(arr);
  },

  getFile(file, isA, cb) {
    let remoteUrl = (isA ? '' : 'https://oss.073c.com/planewar/share/') + file;
    let fullPath = wx.env.USER_DATA_PATH + '/' + (isA ? 'userHead' : file);
    wx.getFileSystemManager().access({
      path: fullPath,
      success: () => {
        console.log('目标资源已经存在');
        cb(null, fullPath);
      },
      fail: () => {
        console.log('download图片路径', remoteUrl, fullPath);
        wx.downloadFile({
          url: remoteUrl,
          filePath: fullPath,
          success: () => {
            console.log('下载成功', fullPath);
            cb(null, fullPath);
          },
          fail: (err) => {
            console.log('下载失败', fullPath);
            cb(err, null);
          }
        });
      }
    });
  },

  //截取字符串长度
  subSectionString(text, cutlen = 12) {
    var id = 0;
    var str = ''
    if (!text) return str;
    var len = 0;
    for (var i = 0; i < text.length; i++) {
      var c = text.charCodeAt(i);
      if (c > 127 || c == 94) {
        len += 2;
      } else {
        len++;
      }
      if (len > cutlen) {
        str += text.substring(id, i);
        return str;
      }
    }
    str += text.substring(id, text.length);
    if (str.length < 2) str += '  ';
    return str;
  },

}

module.exports = SaveImage